// background.js 
/*
chrome.runtime.onInstalled.addListener(() => {
    chrome.tabs.query({currentWindow: true, active : true}, (tabArr) => {
        console.log(tabArr);
        const activeTab = tabArr[0];
        if (!activeTab) {
            console.log('没有拿到 tab')
        }
        chrome.pageAction.show(activeTab.id, () => {
            console.log('激活成功');
        });   
    })

});
*/
var currentTab = null
function isGooglePlayOrDiandianUrl(url) {
    if (url == null) {
        return false;
    }
    if (url.indexOf("play.google.com/store/apps/details?id=") >= 0) {
        return true;
    }
    if (url.indexOf("app.diandian.com") >= 0 && url.indexOf("googleplay") >= 0 && url.indexOf("id=") >= 0) {
        return true;
    }
    return false;
}
chrome.tabs.onActivated.addListener(function (activeInfo) {
    if (activeInfo.tabId) {
        chrome.tabs.get(activeInfo.tabId, function (tab) {
            currentTab = tab
            console.log("id : " + tab.id + " , url : " +  tab.url);
			if (isGooglePlayOrDiandianUrl(tab.url)) {
				chrome.action.enable(tab.id, () => {
					console.log('tab切换激活成功');
				});
			} else {
				chrome.action.disable(tab.id, () => {
					console.log('tab切换隐藏成功');
				});
			}
        });
    }
});
chrome.tabs.onUpdated.addListener(
    function(tabId,changeInfo,tab){
        currentTab = tab
        console.log(tab.url);
        if (isGooglePlayOrDiandianUrl(tab.url)) {
            chrome.action.enable(tab.id, () => {
                console.log('tab更新激活成功');
            });
        } else {
            chrome.action.disable(tab.id, () => {
                console.log('tab更新隐藏成功');
            });
        }
    }
);

chrome.runtime.onMessage.addListener(
    function(request, sender, sendResponse) {
        var appUrl = request.url
        var tabId = request.tabId
        console.log("background add app url : " + appUrl)
        //发起get请求
        var promise = fetch(appUrl).then(function(response) {
            if(response.status === 200){
                return response.json();
            }else{
                return {}
            }
        });
        if (tabId != undefined && tabId != null) {
            sendResponse("succ")
            promise = promise.then(function(data){
                console.log("background tab data : " + data);
                chrome.tabs.sendMessage(tabId,
                    {data: data},
                    function(response) {
                        console.log("background response : " + response);
                    });
            }).catch(function(err){
                console.log(err);
            })
        } else {
            promise = promise.then(function(data){
                console.log("background no tab data : " + data);
                sendResponse(data)
            }).catch(function(err){
                console.log(err);
            })
            return true
        }
    }
);